#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,currentMusicIndex(0)
{
    ui->setupUi(this);
    //设置窗口标题和大小
    setWindowTitle("简易音乐播放器");
    setGeometry(100,100,600,400);

    //创建主部件和布局
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    mainLayout = new QVBoxLayout(centralWidget);

    createMediaPlayer();
    //创建并添加音乐列表
    createMusicList();

    //创建并添加控制按钮
    createControlButtons();

}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::createMusicList()
{
    //音乐列表标签
    listLabel = new QLabel("音乐列表", this);
    listLabel->setStyleSheet("font-size: 14px; font-weight: bold"); //setStyleSheet该函数的作用是什么？
    mainLayout->addWidget(listLabel);

    //音乐列表控件
    musicList = new QListWidget(this);
    musicList->setStyleSheet(R"(
        QListWidget {
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 5px;
            background-color: #f9f9f9;
        }
        QListWidget::item {
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        QListWidget::item:selected {
            background-color: #3498db;
            color: white;
        } )");
    mainLayout->addWidget(musicList);

    //连接列表项点击事件
    connect(musicList, &QListWidget::doubleClicked, this, &MainWindow::playSelectedMusic);
}

void MainWindow::createControlButtons()
{
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    // 添加音乐按钮
    addButton = new QPushButton("添加音乐", this); // 初始化 addButton
    //添加音乐按钮
    addButton->setStyleSheet(R"(
        QPushButton {
            background-color: #2ecc71;
            color: white;
            border-radius: 4px;
            padding: 8px 16px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #27ae60;
        }
    )");

    connect(addButton, &QPushButton::clicked, this, &MainWindow::addMusic);
    buttonLayout->addWidget(addButton);

    //播放按钮
    playButton = new QPushButton("播放", this);
    playButton->setStyleSheet(R"(
        QPushButton {
            background-color: #3498db;
            color: white;
            border-radius: 4px;
            padding: 8px 16px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #2980b9;
        }
    )");
    connect(playButton, &QPushButton::clicked, this, &MainWindow::playMusic); // 连接 playButton 信号到槽
    buttonLayout->addWidget(playButton);
    //暂停按钮
    pauseButton = new QPushButton("暂停", this);
    pauseButton->setStyleSheet(R"(
        QPushButton {
            background-color: #e74c3c;
            color: white;
            border-radius: 4px;
            padding: 8px 16px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #c0392b;
        }
    )");

    connect(pauseButton, &QPushButton::clicked, this, &MainWindow::pauseMusic);
    buttonLayout->addWidget(pauseButton);

    //将按钮布局添加到主布局
    mainLayout->addLayout(buttonLayout);
}

void MainWindow::createMediaPlayer()
{
    player = new QMediaPlayer(this);
    audioOutput = new QAudioOutput(this); // 创建音频输出
    player->setAudioOutput(audioOutput);  // 关联到播放器
    audioOutput->setVolume(1.0);          // 设置默认音量（可选）
    //连接播放器状态变化事件
    // 在 createMediaPlayer 函数中修改信号连接
    connect(player, &QMediaPlayer::playbackStateChanged, this, &MainWindow::updatePlayButton);
    //连接播放器状态变化事件，用于处理播放完的自动切换下一首
    connect(player, &QMediaPlayer::mediaStatusChanged, this, &MainWindow::handleMediaStatusChanged);
}

void MainWindow::playSelectedMusic(const QModelIndex &index)
{
    QString selectedMusic = musicList->item(index.row())->text();
    for (int i = 0; i < musicPathList.size(); ++i){
        if(QFileInfo(musicPathList[i]).fileName() == selectedMusic){
            currentMusicIndex = i;
            player->setSource(QUrl::fromLocalFile(musicPathList[currentMusicIndex]));
            if (player->error() != QMediaPlayer::NoError) {
                // 处理错误
                qDebug() << "Failed to set media source:" << player->errorString();
                return;
            }
            player->play();
            if (player->error() != QMediaPlayer::NoError) {
                // 处理错误
                qDebug() << "Failed to play media:" << player->errorString();
            }
            break;
        }
    }
}

void MainWindow::updatePlayButton(QMediaPlayer::PlaybackState state)
{
    if (state == QMediaPlayer::PlayingState) {
        playButton->setEnabled(false);
        pauseButton->setEnabled(true);
    } else {
        playButton->setEnabled(true);
        pauseButton->setEnabled(false);
    }
}

// 添加媒体状态变化的调试输出
void MainWindow::handleMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    qDebug() << "媒体状态变化：" << status;

    switch (status) {
    case QMediaPlayer::LoadedMedia:
        qDebug() << "媒体已加载";
        break;
    case QMediaPlayer::BufferingMedia:
        qDebug() << "媒体缓冲中...";
        break;
    case QMediaPlayer::StalledMedia:
        qDebug() << "媒体播放停滞";
        break;
    case QMediaPlayer::EndOfMedia:
        qDebug() << "媒体播放结束";
        // 处理播放下一首
        break;
    case QMediaPlayer::InvalidMedia:
        qDebug() << "无效媒体：" << player->errorString();
        break;
    default:
        break;
    }

    if (status == QMediaPlayer::EndOfMedia) {
        currentMusicIndex++;
        if (currentMusicIndex < musicPathList.size()) {
            playMusic();
        }
    }
}

// 在 addMusic() 函数中添加调试输出
void MainWindow::addMusic()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(
        this, "选择音乐文件", "", "音频文件 (*.mp3 *.wav *.ogg *.flac);;所有文件 (*)"
        );

    for (const QString &fileName : fileNames) {
        // 获取文件名（不包含路径）
        QString fileNameShort = QFileInfo(fileName).fileName();
        // 添加到音乐列表
        musicList->addItem(fileNameShort);
        // 保存文件路径到列表
        musicPathList.append(fileName);

        // 调试输出
        qDebug() << "添加音乐：" << fileNameShort << "，完整路径：" << fileName;
    }

    // 显示添加的音乐数量
    qDebug() << "共添加" << musicPathList.size() << "首音乐";
}
void MainWindow::playMusicAtIndex(int index)
{
    if (index < 0 || index >= musicPathList.size()) {
        qDebug() << "错误：当前音乐索引超出范围";
        return;
    }

    const QString &filePath = musicPathList[index];

    // 验证文件是否存在
    if (!QFile::exists(filePath)) {
        qDebug() << "错误：文件不存在 - " << filePath;
        return;
    }

    qDebug() << "尝试播放：" << filePath;

    // 重置播放器状态
    player->stop();
    player->setSource(QUrl::fromLocalFile(filePath));

    // 检查设置源是否成功
    if (player->error() != QMediaPlayer::NoError) {
        qDebug() << "设置媒体源失败：" << player->errorString();
        qDebug() << "媒体源 URL：" << player->source().toString();
        return;
    }

    // 输出媒体状态
    qDebug() << "媒体状态：" << player->mediaStatus();

    // 尝试播放
    player->play();

    // 再次检查错误
    if (player->error() != QMediaPlayer::NoError) {
        qDebug() << "播放失败：" << player->errorString();
    } else {
        qDebug() << "播放已开始";
    }


}
void MainWindow::playMusic()
{
    playMusicAtIndex(currentMusicIndex);
}

void MainWindow::pauseMusic()
{
    player->pause();
}
